<template>
  <div>
    <!-- 导航栏区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert center title="添加商品信息" type="info" :closable="false" show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex*1" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧tab栏 -->
      <el-form label-position="top" label-width="100px" :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-tabs v-model="activeIndex" tab-position="left" :before-leave="beforeTabLeave" @tab-click="tabclickInit">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" class="is-required" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" class="is-required" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" class="is-required" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" class="is-required" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" class="is-required" prop="goods_cat">
              <!-- 多层分级区域 -->
              <el-cascader :options="cateList" v-model="addForm.goods_cat" :props="eascaderList" clearable
                @change="handleChange" placeholder="请选择">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染item项 -->
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="obj" v-for="(obj,ind) in item.attr_vals1" :key="ind" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload list-type="picture" :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
              :headers="headerObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本 -->
            <quill-editor v-model="addForm.goods_introduce" style="width:78%"></quill-editor>
            <el-button type="primary" style="margin-top:15px" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" width="50%" :visible.sync="previewVisible">
      <img :src="previewPath" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Add',
  data () {
    return {
      // 图片储存路径
      previewPath: '',
      // 图片对话框显示隐藏属性
      previewVisible: false,
      // 图片的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      uploadURL: 'http://42.192.71.221:8889/api/private/v1/upload',
      activeIndex: '0',   // 激活索引
      // 添加商品的表单对象
      addForm: {
        goods_name: '',
        goods_number: 0,
        goods_weight: 0,
        goods_price: 0,
        goods_cat: [],
        // 图片上传数组
        pics: [],
        // 商品描述
        goods_introduce: '',
        attrs: [],  //  包含动态参数和静态属性
      },
      addFormRules: {
        goods_name: [
          { require: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { require: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { require: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { require: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      // 商品分类
      cateList: [],
      eascaderList: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 动态参数
      manyTableData: [],
      // 静态属性
      onlyTableData: [],
    }
  },
  methods: {
    // 添加商品
    add () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填必要的表单项')
        }
        // goods_cat为数组 提交时需转换为字符串
        this.addForm.goods_cat = this.addForm.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_value: item.attr_vals,
            attr_id: item.attr_id
          }
          this.addForm.attrs.push(newInfo)
        })
        // addForm需要转化为form表单形式  与接口保持一致
        const form = this.addForm
        form.attrs = this.addForm.attrs
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success(res.meta.msg)
        // 成功之后跳转到商品列表查看
        this.$router.push('/goods')
      })
    },
    // 监听图片上传成功方法
    handleSuccess (response) {
      // 图片上传格式  与后台接口要求格式保持一致
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    // 删除图片
    handleRemove (field) {
      // 查找数组中的临时路径
      const fieldPath = field.response.data.tmp_path
      // 查找索引
      const i = this.addForm.pics.findIndex(item => item.pic === fieldPath)
      // 进行删除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm);
    },
    // 图片预览效果
    handlePreview (file) {
      console.log(file);
      // 路径为url的完整路径  tem_path为临时路径
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 获取动态参数
    async tabclickInit () {
      //   console.log(this.activeIndex);
      // 条件判断是否点击为动态参数
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$message.error('获取动态参数失败')
        // 服务器返回的attr_vals是字符串  需要转换为数组
        res.data.forEach(item => {
          item.attr_vals1 = item.attr_vals = item.attr_vals === 0 ? [] : item.attr_vals.split(',')
        })
        this.manyTableData = res.data
        // console.log(res.data);
      } else if (this.activeIndex === '2') {
        // 静态属性
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$message.error('获取静态属性失败')
        this.onlyTableData = res.data
      }
    },
    // tab栏的钩子函数进行条件阻拦
    beforeTabLeave (activeName, oldActiveName) {
      // console.log(oldActiveName);
      // console.log(activeName);
      if (this.addForm.goods_cat.length !== 3 && oldActiveName === '0') {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 改变选择绑定事件
    handleChange () {
      //   console.log(this.addForm.goods_cat);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 获取商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.cateList = res.data
    },
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style lang='less' scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
/deep/.el-step__title {
  font-size: 12px;
}
/deep/.el-checkbox {
  margin: 0;
}
/deep/.el-upload-list {
  width: 78%;
}
/deep/.ql-editor {
  min-height: 300px;
}
</style>